package com.prawn.education.service;

import com.prawn.education.dao.IntellectualPropertyRightsTypesDao;
import com.prawn.education.dao.TypeDao;
import com.prawn.education.pojo.IntellectualPropertyRightsTypes;
import com.prawn.education.pojo.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;
import java.util.Optional;

/**
 * 服务层
 *
 * @author Administrator
 */
@Service
public class IntellectualPropertyRightsTypesService {

    @Autowired
    private IntellectualPropertyRightsTypesDao typeDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 增加
     *
     * @param type
     */
    public void add(IntellectualPropertyRightsTypes type) {
        type.setId(idWorker.nextId() + "");
        if (type.getLevel() != 1 && type.getLevel() != 2)
            type.setLevel(1);
        if (type.getLevel() == 1)
            type.setParentId("");
        type.setState(true);
        typeDao.save(type);
    }

    /**
     * 修改
     *
     * @param type
     */
    public void update(IntellectualPropertyRightsTypes type) {
        if (type.getLevel() != 1 && type.getLevel() != 2)
            type.setLevel(1);
        if (type.getLevel() == 1)
            type.setParentId("");
        type.setState(true);
        typeDao.save(type);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        Optional<IntellectualPropertyRightsTypes> type = typeDao.findById(id);
        type.get().setState(false);
        typeDao.save(type.get());
    }

    public Optional<IntellectualPropertyRightsTypes> findById(String id) {
        return typeDao.findByIdAndStateTrue(id);
    }

    public Page<IntellectualPropertyRightsTypes> findAll(int page, int size) {
        return typeDao.findByStateTrue(PageRequest.of(page - 1, size));
    }


    public Page<IntellectualPropertyRightsTypes> findByLevel(int level, int page, int size) {
        return typeDao.findByLevelAndStateTrue(level, PageRequest.of(page - 1, size));
    }

    public Page<IntellectualPropertyRightsTypes> findByParentId(String parentId, int page, int size) {
        return typeDao.findByParentIdAndStateTrue(parentId, PageRequest.of(page - 1, size));
    }
}
